<?php
/**
 * User: huayi.cai
 * Date: 2015/5/20
 * Time: 10:05
 */
include_once dirname(dirname(__FILE__)).'/nn_logic/nl_dc.class.php';
include_once dirname(dirname(__FILE__)).'/nn_logic/queue/queue.class.php';
include_once dirname(dirname(__FILE__)).'/nn_logic/queue/queue_pool.class.php';
include_once dirname(dirname(__FILE__)).'/nn_logic/queue/queue_redis.class.php';
include_once dirname(dirname(__FILE__)).'/nn_logic/cp/cp.class.php';
include_once dirname(dirname(__FILE__)).'/nn_logic/sp/sp.class.php';
include_once dirname(dirname(__FILE__)).'/nn_logic/project_group/project_group.class.php';
include_once dirname(dirname(__FILE__)).'/nn_logic/project_group/project_key.class.php';
include_once dirname(dirname(__FILE__)).'/nn_logic/project_group/project_model.class.php';
include_once dirname(dirname(dirname(__FILE__))) .'/np/np_http_curl.class.php';
include_once dirname(dirname(dirname(__FILE__))) .'/np/np_xml2array.class.php';
class nn_timer
{
	private $timer_name = "";
	private $timer_model = "";
	private $process_num = 0;
	private $base_path = null;
	private $base_path_1 = null;
	private $last_run_time = false; //上一次开始执行时间，对于一些获取数据的脚本有用，格式时间戳
	private $the_run_time = false; //本次开始执行时间
	private $file_path = null; //本次开始执行时间
	const max_execute_time = 1800;
	private $timer_queue_pool = null;
	public $obj_dc = null;
    public $obj_redis = null;
    
    public $arr_params = null;
    
    public $g_arr_queue_pool = null;
    
    public $g_debug_sql_enable = 0;
    
    public $arr_cp_config = null;
    
    public $arr_sp_config = null;
    
    /**
     * 默认没开启队列池
     * @var unknown
     */
    public $flag_queue_pool = FALSE;

	public function __construct($timer_name, $timer_model,$file_path=null,$timer_pool=null)
	{
		nx_dispatch_debuger();
		$this->base_path = dirname(dirname(__FILE__));
		$this->base_path_1 = dirname(dirname(dirname(__FILE__)));
		$this->timer_name = "timer_" . $timer_name;
		$this->timer_model = $timer_model;
		$this->process_num = rand(0, 100000);
		$this->file_path = strlen($file_path) ? $file_path : null;
		
		if(strlen($timer_pool) >0 && !is_null($timer_pool))
		{
		    global $g_arr_queue_pool;
        $this->msg("[redis池中返回数据为:]".var_export($g_arr_queue_pool, true));
		    $g_arr_queue_pool;
		    $arr_queue_pool = null;
		    if(is_array($g_arr_queue_pool))
		    {
		        foreach ($g_arr_queue_pool as $val)
		        {
		            $arr_queue_pool[$val['name']] = $val;
		        }
		    }
		    unset($g_arr_queue_pool);
		    $this->g_arr_queue_pool = $arr_queue_pool;
		    $this->obj_dc = nl_get_dc(array (
                'db_policy' => NL_DB_WRITE,
                'cache_policy' => NP_KV_CACHE_TYPE_NULL
            ));
		    $this->obj_redis = nl_get_redis();
		    $this->timer_queue_pool = $timer_pool;
		}
		global $g_debug_sql_enable;
		if(isset($g_debug_sql_enable) && $g_debug_sql_enable == 1)
		{
		    $this->msg("-----------SQL语句收集脚本开关开启------------");
		    nl_dc::$db_debug_enable = $this->g_debug_sql_enable = 1;
		}
		else
		{
		    $this->msg("-----------SQL语句收集脚本开关关闭------------");
		}
		unset($g_debug_sql_enable);
	//	register_shutdown_function(array($this, 'set_running_flag'),0);
	}
	
	
	
	/**
	 * 获取CP信息
	 * @param unknown $cp_id
	 */
	public function _get_cp_info($cp_id)
	{
	    if(strlen($cp_id) <1)
	    {
	        return $this->return_data(1, '$cp_id为空');
	    }
	    if(isset($this->arr_cp_config[$cp_id]))
	    {
	        return $this->return_data(0, 'ok');
	    }
	    $result_cp = nl_cp::query_by_id($this->obj_dc,$cp_id);
	    if($result_cp['ret'] !=0)
	    {
	        return $result_cp;
	    }
	    if(!isset($result_cp['data_info']) || !is_array($result_cp['data_info']) || empty($result_cp['data_info']))
	    {
	        $this->arr_cp_config[$cp_id] = null;
	        return $result_cp;
	    }
	    if($this->is_json($result_cp['data_info']['nns_config']))
	    {
	        $result_cp['data_info']['nns_config'] = json_decode($result_cp['data_info']['nns_config'],true);
	    }
	    $this->arr_cp_config[$cp_id]=$result_cp['data_info'];
	    return $result_cp;
	}
	
	/**
	 * 获取CP信息
	 * @param unknown $cp_id
	 */
	public function _get_sp_info($sp_id)
	{
	    if(strlen($sp_id) <1)
	    {
	        return $this->return_data(1, '$sp_id为空');
	    }
	    if(isset($this->arr_sp_config[$sp_id]))
	    {
	        if(!isset($this->arr_sp_config[$sp_id]['nns_config']['epg_url']) || strlen($this->arr_sp_config[$sp_id]['nns_config']['epg_url']) <1)
	        {
	            return $this->return_data(1, 'EPG注入点播接口未配置');
	        }
	        return $this->return_data(0, 'ok');
	    }
	    $result_sp = nl_sp::query_by_id($this->obj_dc,$sp_id);
	    if($result_sp['ret'] !=0)
	    {
	        return $result_sp;
	    }
	    if(!isset($result_sp['data_info'][0]) || !is_array($result_sp['data_info'][0]) || empty($result_sp['data_info'][0]))
	    {
	        $this->arr_sp_config[$sp_id] = null;
	        return $result_sp;
	    }
	    if($this->is_json($result_sp['data_info'][0]['nns_config']))
	    {
	        $result_sp['data_info'][0]['nns_config'] = json_decode($result_sp['data_info'][0]['nns_config'],true);
	    }
	    $this->arr_sp_config[$sp_id]=$result_sp['data_info'][0];
	    if(!isset($this->arr_sp_config[$sp_id]['nns_config']['epg_url']) || strlen($this->arr_sp_config[$sp_id]['nns_config']['epg_url']) <1)
	    {
	        return $this->return_data(1, 'EPG注入点播接口未配置');
	    }
	    return $result_sp;
	}
	
	
	/**
	 * 获取所有sP信息
	 * @param unknown $cp_id
	 */
	public function _get_all_sp_info()
	{
	    $result_sp = nl_sp::query_all($this->obj_dc);
	    if($result_sp['ret'] !=0 || !isset($result_sp['data_info']) || !is_array($result_sp['data_info']) || empty($result_sp['data_info']))
	    {
	        return $result_sp;
	    }
	    foreach ($result_sp['data_info'] as $sp_val)
	    {
	        if($this->is_json($sp_val['nns_config']))
	        {
	            $sp_val['nns_config'] = json_decode($sp_val['nns_config'],true);
	        }
	        $this->arr_sp_config[$sp_val['nns_id']] = $sp_val;
	    }
	    return $result_sp;
	}
	
	
	/**
	 * 获取所有CP信息
	 * @param unknown $cp_id
	 */
	public function _get_all_cp_info()
	{
	    $result_cp = nl_cp::query_all($this->obj_dc);
	    if($result_cp['ret'] !=0 || !isset($result_cp['data_info']) || !is_array($result_cp['data_info']) || empty($result_cp['data_info']))
	    {
	        return $result_cp;
	    }
	    foreach ($result_cp['data_info'] as $cp_val)
	    {
	        if($this->is_json($cp_val['nns_config']))
	        {
	            $cp_val['nns_config'] = json_decode($cp_val['nns_config'],true);
	        }
	        $this->arr_cp_config[$cp_val['nns_id']] = $cp_val;
	    }
	    return $result_cp;
	}

	/**
	 * 全局参数检查哈
	 */
	public function _global_validate_config_info()
    {
        if(!is_array($this->g_arr_queue_pool))
        {
            return $this->_return_data(1,'全局配置g_arr_queue_pool 未配置');
        }
        if(!isset($this->g_arr_queue_pool[$this->timer_queue_pool]))
        {
            return $this->_return_data(1,"全局配置g_arr_queue_pool[".$this->timer_queue_pool."] 未配置");
        }
        $temp_arr_queue_pool = $this->g_arr_queue_pool[$this->timer_queue_pool];
        if(!isset($temp_arr_queue_pool['ext_info']) || !is_array($temp_arr_queue_pool['ext_info']) || empty($temp_arr_queue_pool['ext_info']))
        {
            return $this->_return_data(0,"OK");
        }
        foreach ($temp_arr_queue_pool['ext_info'] as $temp_value)
        {
            switch ($temp_value['rule'])
            {
                case 'noempty':
                    if(!isset($this->arr_params['bk_queue_config']['nns_ext_info'][$temp_value['name']]) || strlen($this->arr_params['bk_queue_config']['nns_ext_info'][$temp_value['name']]) <1)
                    {
                        return $this->_return_data(1,"全局配置g_arr_queue_pool[".$this->timer_queue_pool."][".$temp_value['name']."] 为空");
                    }
                    break;
                case 'int':
                    if(!isset($this->arr_params['bk_queue_config']['nns_ext_info'][$temp_value['name']]) || strlen($this->arr_params['bk_queue_config']['nns_ext_info'][$temp_value['name']]) <1 || $this->arr_params['bk_queue_config']['nns_ext_info'][$temp_value['name']] <1)
                    {
                        return $this->_return_data(1,"全局配置g_arr_queue_pool[".$this->timer_queue_pool."][".$temp_value['name']."] 不在数值范围内");
                    }
                    break;
            }
        }
        return $this->_return_data(0,"OK");
    }
    
    /**
     * 
     * @param unknown $string
     * @return boolean
     */
    public function has_length($string)
    {
        if(!is_string($string))
        {
            return false;
        }
        $string = strlen($string) < 1 ? '' : trim($string);
        if(strlen($string) <1)
        {
            return false;
        }
        return true;
    }
    
    /**
     * 判断是否是json
     * @param unknown $string
     * @return boolean
     */
    public function is_json($string)
    {
        $string = strlen($string) <1 ? '' : $string;
        json_decode($string);
        return (json_last_error() == JSON_ERROR_NONE);
    }
    
    /**
     * 队列池数据验证 检查 数据是否该修改，删除，和添加
     * @param unknown $queue_val
     */
    public function _check_all_params($queue_val,$arr_data,$arr_exsist=null,$flag=FALSE)
    {
        if(!is_array($arr_data) || empty($arr_data))
        {
            return $this->_return_data(0,'传入的对比参数为空');
        }
        $arr_add = $arr_edit = $arr_del = null;
        if(!$flag)
        {
            $result_queue_exsist = nl_queue_pool::timer_query_by_queue_id_v2($this->obj_dc,$queue_val['nns_id']);
            if($result_queue_exsist['ret'] !=0)
            {
                return $result_queue_exsist;
            }
            
            $result_queue_exsist = (isset($result_queue_exsist['data_info']) && is_array($result_queue_exsist['data_info']) && !empty($result_queue_exsist['data_info'])) ? $result_queue_exsist['data_info'] : null;
            if(is_array($result_queue_exsist))
            {
                foreach ($result_queue_exsist as $exsist_val)
                {
                    $arr_exsist[$exsist_val['nns_value']] = $exsist_val;
                }
            }
        }
        $arr_ex_keys = array_keys($arr_data);
        if(is_array($arr_exsist))
        {
            foreach ($arr_exsist as $exsist_key=>$exs_val)
            {
                if(!in_array($exsist_key, $arr_ex_keys))
                {
                    $arr_del[] = $exsist_key;
                    unset($arr_exsist[$exsist_key]);
                }
            }
        }
        foreach ($arr_data as $data_key=>$data_val)
        {
            if(isset($arr_exsist[$data_key]))
            {
                if($data_val['nns_state'] == $data_val['nns_state'])
                {
                    continue;
                }
                $arr_edit[$data_val['nns_state']][] = $data_key;
            }
            else
            {
                $arr_add[$data_key] = $data_val;
            }
        }
        if(is_array($arr_del) && !empty($arr_del))
        {
            $result_queue_pool = nl_queue_pool::delete_by_value($this->obj_dc, $queue_val['nns_id'], $arr_del);
            if($result_queue_pool['ret'] !=0)
            {
                return $result_queue_pool;
            }
        }
        if(is_array($arr_edit) && !empty($arr_edit))
        {
            foreach ($arr_edit as $edit_key=>$edit_val)
            {
                $result_edit = nl_queue_pool::edit_v2($this->obj_dc, array('nns_state'=>$edit_key), array('nns_queue_id'=>$queue_val['nns_id'],'nns_value'=>$edit_val));
                if($result_edit['ret'] !=0)
                {
                    return $result_edit;
                }
            }
        }
        if(is_array($arr_add) && !empty($arr_add))
        {
            return $this->push_to_queue_pool_mysql($queue_val, $arr_add);
        }
        return $this->_return_data(0,'OK');
    }
    
	
	/**
	 * 定时器运行
	 * @param string $params
	 */
	public function run($params = NULL)
	{
		
		$result_check = $this->_return_data(0,'ok');
		if(strlen($this->timer_queue_pool) >0)
		{
		    $result = nl_queue::timer_query_by_queue_id($this->obj_dc, $this->timer_queue_pool);
		    if($result['ret'] !=0 || !isset($result['data_info']) || empty($result['data_info']) || !is_array($result['data_info']))
		    {
		        $result_check = $this->_return_data(999,"查询队列池数据库执行失败|或者队列池失效".var_export($result,true));
		    }
		    else
		    {
		        $result = $result['data_info'];
		        $result['nns_ext_info'] = (isset($result['nns_ext_info']) && strlen($result['nns_ext_info']) >0) ? json_decode($result['nns_ext_info'],true) : null;
		        $params['bk_queue_config'] = $result;
		        $this->flag_queue_pool = true;
		        
		        $result_redis_pop = nl_queue_redis::pop($this->obj_redis, $this->timer_queue_pool);
		        $temp_queue_val = (isset($result_redis_pop['data_info']) && strlen($result_redis_pop['data_info'])>0) ? $result_redis_pop['data_info'] : '';
		        if(strlen($temp_queue_val) <1)
		        {
		            $result_redis_pop = nl_queue_redis::pop($this->obj_redis, $this->timer_queue_pool);
		            $temp_queue_val = (isset($result_redis_pop['data_info']) && strlen($result_redis_pop['data_info'])>0) ? $result_redis_pop['data_info'] : '';
		        }
		        if (strlen($temp_queue_val)<1)
		        {
		            $this->msg("队列查询两次值都为空有问题啊");
		            return ;
		        }
		        $params['bk_queue_value'] = $temp_queue_val;
		        $this->msg("执行队列池[{$this->timer_queue_pool}]值[{$temp_queue_val}]");
		        $this->arr_params = $params;
		        $result_check = $this->_global_validate_config_info();
		    }
		}
		if(!$this->check_linux_course())
		{
		    $this->msg("/* " . date("Y-m-d H:i:s") . " 进程还在运行-----定时器脚本结束 */");
		    return ;
		}
		if($result_check['ret'] == '0')
		{
		    $this->action($params);
		    if(strlen($this->timer_queue_pool) >0 && isset($result['nns_often_state']) && $result['nns_often_state'] !='1')
		    {
                $result_queue_pool = nl_queue_redis::get_list(nl_get_redis(), $this->timer_queue_pool);
                $result_queue_pool = (isset($result_queue_pool['data_info']) && is_array($result_queue_pool['data_info']) && !empty($result_queue_pool['data_info'])) ? $result_queue_pool['data_info'] : array();
                if(!in_array($temp_queue_val, $result_queue_pool))
                {
                    $result_redis_push = nl_queue_redis::push(nl_get_redis(), $this->timer_queue_pool,$temp_queue_val);
                    if($result_redis_push['ret'] !=0)
                    {
                        $this->msg("redis队列插入数据有问题咯,模板[{$this->timer_queue_pool}],值[{$temp_queue_val}]");
                    }
                }
		    }
		}
		else if($result_check['ret'] == '999')
		{
		    $this->msg($result_check['reason'].'----------走原来的队列逻辑');
		    $this->action($params);
		}
		else
		{
		    $this->msg($result_check['reason']);
		}
		$this->collect_sql();
	}

	/**
	 * 收集 debug sql
	 */
	public function collect_sql()
	{
	    if($this->g_debug_sql_enable !=1)
	    {
	        return ;
	    }
	    $this->msg("/*SQL语句收集脚本开始 */");
	    global $g_debug_sql_ex_second;
	    $debug_sql_ex_second = (isset($g_debug_sql_ex_second) && $g_debug_sql_ex_second >=0) ? ($g_debug_sql_ex_second*1000) : 5000;
	    unset($g_debug_sql_ex_second);
	    if (!is_array(nl_dc::$db_debug_arr))
	    {
	        $this->msg("/*无任何SQL语句 */");
	        $this->msg("/*SQL语句收集脚本结束 */");
	        return ;
	    }
	    
	    foreach (nl_dc::$db_debug_arr as $db)
	    {
	        $config=$db->get_db_config();
	        $host_ip=$config['host'];
	        $debug_info=$db->get_db_debug();
	        
	        if($debug_sql_ex_second >0)
	        {
	            $this->write_sql_log("/*收集>={$debug_sql_ex_second}ms的sql语句 */");
	            foreach ($debug_info as $debug)
	            {
	                $time=round($debug['time']*1000,3);
	                if($time >= $debug_sql_ex_second)
	                {
	                    $this->write_sql_log("执行时间[{$time}ms]:".$debug['SQL'],$debug);
	                }
	            }
	        }
	        else
	        {
	            $this->write_sql_log("/* 收集全部sql语句 */");
	            $time=round($debug['time']*1000,3);
	            foreach ($debug_info as $debug)
	            {
	                 $this->write_sql_log("执行时间[{$time}ms]:".$debug['SQL'],$debug);
	            }
	        }
	    }
	    $this->msg("/*SQL语句收集脚本结束 */");
	}
	
	
	
	/**
	 * 推入队列池redis
	 */
	public function push_to_queue_pool_redis($queue_val)
	{
	    $result_query = nl_queue_pool::timer_query_by_queue_id($this->obj_dc,$queue_val['nns_id']);
	    if($result_query['ret']!=0 || !isset($result_query['data_info']) || empty($result_query['data_info']) || !is_array($result_query['data_info']))
	    {
	        return $result_query;
	    }
	    $result_query = $result_query['data_info'];
	    $redis_data = array();
	    foreach ($result_query as $query_val)
	    {
	        $redis_data[] = $query_val['nns_value'];
	    }
	    $result_queue_pool = nl_queue_redis::get_list(nl_get_redis(), $queue_val['nns_queue']);
	    $result_queue_pool = (isset($result_queue_pool['data_info']) && is_array($result_queue_pool['data_info']) && !empty($result_queue_pool['data_info'])) ? $result_queue_pool['data_info'] : array();
	    $redis_data = array_diff($redis_data,$result_queue_pool);
	    if(is_array($redis_data) && !empty($redis_data))
	    {
	        foreach ($redis_data as $redis_data_val)
	        {
	            $result_add_redis = nl_queue_redis::push(nl_get_redis(), $queue_val['nns_queue'], $redis_data_val);
	            if($result_add_redis['ret'] !=0)
	            {
	                return $result_add_redis;
	            }
	        }
	    }
	    return $this->_return_data(0,'ok');
	}
	
	
	/**
	 * 推入队列池mysql
	 * @param unknown $queue_val
	 * @param unknown $arr_insert_data
	 * @return Ambigous|array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
	 */
	public function push_to_queue_pool_mysql($queue_val,$arr_insert_data)
	{
	    if(empty($queue_val) || !is_array($queue_val))
	    {
	        return $this->_return_data(1,'队列模板参数非数组：'.var_export($queue_val,true));
	    }
	    if(empty($arr_insert_data) || !is_array($arr_insert_data))
	    {
	        return $this->_return_data(1,'队列参数非数组：'.var_export($arr_insert_data,true));
	    }
        $arr_insert_data = array_chunk($arr_insert_data,100,true);
        foreach ($arr_insert_data as $val)
        {
            $temp_array_keys = array_keys($val);
            $result_exsist = nl_queue_pool::query_by_queue_value_id($this->obj_dc, $queue_val['nns_id'], $temp_array_keys);
            if($result_exsist['ret'] !=0)
            {
                continue;
            }
            if(isset($result_exsist['data_info']) && !empty($result_exsist['data_info']) && is_array($result_exsist['data_info']))
            {
                foreach ($result_exsist['data_info'] as $exist_val)
                {
                    if(isset($val[$exist_val['nns_value']]))
                    {
                        unset($val[$exist_val['nns_value']]);
                    }
                }
            }
            if(empty($val) || !is_array($val))
            {
                continue;
            }
            $val = array_values($val);
            $result_add_mysql = nl_queue_pool::add($this->obj_dc, $val);
            if($result_add_mysql['ret'] !=0)
            {
                continue;
            }
        }
	    return $this->_return_data(0,'ok');
	}
	
	protected function action($params = null)
	{
		//        do something....
	}

	public function set_sql_log()
	{
		
		
		if (is_array(nl_dc::$db_debug_arr))
		{
			foreach (nl_dc::$db_debug_arr as $db){
				$config=$db->get_db_config();
				$host_ip=$config['host'];
				$debug_info=$db->get_db_debug();
				foreach ($debug_info as $debug){
					//     				var_dump(strtolower(strpos($debug['SQL']), "nns_mgtvbk_c2_task"),'testtesttest');
					if(strpos(strtolower($debug['SQL']), "nns_mgtvbk_c2_task") === false)
					{
						//     					continue;
					}
					$re=array();
// 					$re['ip']=$host_ip;
					$re['sql']=$debug['SQL'];
// 					$re['desc']=$debug['debug'];
					$re['time']=round($debug['time']*1000,3);
// 					$re['explain_debug']=$debug['explain_debug'];
// 					$result['data'][]=$re;
				}
			}
		}
	}
	
	public function write_sql_log($msg,$debug=null)
	{
		$control_file = $this->base_path . "/data/log/nn_timer/" . $this->timer_model . "/" . $this->timer_name . ".sql";
		$str_log_dir = dirname($control_file);
		if (!is_dir($str_log_dir))
		{
			mkdir($str_log_dir, 0777, true);
		}
		$msg = $msg . "\n";
		echo $msg ;
		echo (isset($debug['debug']) && $debug['debug'] =='OK') ? '' : "<font color='red'>{$debug['debug']}</font>";
		echo "\r\n<br/>";
		@error_log($msg, 3, $control_file);
		unset($msg);
		return;
	}
	
	public function set_running_flag($state)
	{
		$control_file = $this->base_path . "/data/log/nn_timer/" . $this->timer_model . "/" . $this->timer_name . ".txt";
		$str_log_dir = dirname($control_file);
		if (!is_dir($str_log_dir))
		{
			mkdir($str_log_dir, 0777, true);
		}
		$datetime = date("YmdHis", $this->the_run_time);
		$controls = $state . ',' . $datetime;
		file_put_contents($control_file, $controls);
	}

	private function check_running_flag()
	{
		$control_file = $this->base_path . "/data/log/nn_timer/" . $this->timer_model . "/" . $this->timer_name . ".txt";
		if (!defined("CONTROL_STATIC_RUNNING_LOCK_MAX_TIME"))
		{
			$control_times = self::max_execute_time;
		}
		else
		{
			$control_times = CONTROL_STATIC_RUNNING_LOCK_MAX_TIME;
		}
		$this->msg("检查上一次脚本是否已经停止运行");
		
		$this->the_run_time = time(); //定本次脚本执行开始时间
		

		if (!file_exists($control_file))
		{
			$this->set_running_flag(1);
			return TRUE;
		}
		
		$control_content = @file_get_contents($control_file);
		$control_content = trim($control_content);
		$control_contents = explode(",", $control_content);
		
		$this->last_run_time = strtotime($control_contents[1]);
		
		if ($control_contents[0] == 0)
		{
			$this->msg("上一次脚本已经停止运行, 执行时间：" . $control_contents[1]);
			$this->set_running_flag(1);
			return TRUE;
		}
		if ($control_contents[0] == 1 && ($this->the_run_time - $this->last_run_time >= $control_times))
		{
			$this->msg("上一次脚本还在运行，但运行了{$control_times}秒，可能是PHP卡死");
			$this->set_running_flag(1);
			return TRUE;
		}
		$this->msg("上一次脚本还在运行");
		return FALSE;
	}

	/**
     * 获取脚本上一次的执行开始时间
     * @return boolean false 表示本次是第一次执行 | 时间戳
     */
	public function get_last_run_time()
	{
		return $this->last_run_time;
	}

	/**
     * 获取脚本本次的执行开始时间
     * @return 时间戳
     */
	public function get_the_run_time()
	{
		return $this->the_run_time;
	}

	/**
	 * 判断定时器脚本是否多进程运行
	 * @param string $str_course_file_name 定时器脚本  进程查询的 相对|绝对路径
	 * @return boolean true | false
	 * @author liangpan
	 * @date 2015-08-05
	 */
	public function check_linux_course()
	{
// 		$arr_file = debug_backtrace();
// 		$arr_file = array_pop($arr_file);
// 		$str_course_file_name = $arr_file['file'];
        if($this->flag_queue_pool)
        {
            return true;
        }
        $str_course_file_name = str_replace($this->base_path_1.'/', '', $this->file_path);
		$this->msg("-------进程查询处理开始-------");
		$str_course_file_name = "ps -ef | grep " . $str_course_file_name . " | grep -v grep | awk '{print $2}'";
		$this->msg("进程查询的命令为：" . $str_course_file_name);
		@exec($str_course_file_name,$arr_course,$exec_result);
		$this->msg("进程查询的结果为：" . var_export($arr_course,true));
		if($exec_result != 0)
		{
			global $g_ignore_exec_error;
			$return = $g_ignore_exec_error ? false : true;
			unset($g_ignore_exec_error);
			$str_desc = $return ? "程序忽略定时器进程控制，继续执行" : "程序需要定时器进程控制，停止执行";
			$this->msg("进程查询php报错，可能是关闭了exec，也可能没在linux环境运行....".$str_desc);
			return $return;
		}
		if (!empty($arr_course))
		{
			$count_course =count($arr_course);
			if($count_course == 1)
			{
				$this->msg("运行的进程有".$count_course."个，进程正常");
				return true;
			}
			else
			{
				$this->msg("运行的进程有".$count_course."个，结束进程");
				return false;
			}
		}
		else
		{
			$this->msg("一个进程都没开启，继续执行");
			return true;
		}
		$this->msg("-------进程查询处理结束-------");
	}
	
	public function msg($msg)
	{
		if (empty($msg))
		{
			return;
		}
		//写入日志文件
		$str_log_dir = $this->base_path . '/data/log/nn_timer/' . $this->timer_model . '/' . $this->timer_name . '/' . date("Ymd") . "/";
		$str_log_file = date("H") . '.txt';
		$str_start_time = "[{$this->process_num}][" . date("Y-m-d H:i:s") . "]";
		echo $str_start_time . " " . $msg . "\r\n<br/>";
		if (!is_dir($str_log_dir))
		{
			mkdir($str_log_dir, 0777, true);
			if(strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')
			{
    			$stat = stat($str_log_dir);
    			$result_chown = (posix_getpwuid($stat['uid']));
    			if(!isset($result_chown['name']) || $result_chown['name'] != 'www')
    			{
    			    chown($result_chown, 'www');
    			}
			}
		}
		file_put_contents($str_log_dir . $str_log_file, $str_start_time . $msg . "\r\n", FILE_APPEND);
		return;
	}
	
	public function __destruct()
	{
		nx_output_debug_info();
	}
	
	
	/**
	 * 公共返回数据
	 * @param number $ret 状态码
	 * @param string $reason 原因描述
	 * @param array|string $data 返回数据
	 * @param array $page_data 分页数据
	 * @param array $other_data 其他扩展数据
	 * @return array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
	 * @author liangpan
	 * @date 2015-09-07
	 */
	public function _return_data($ret,$reason=null,$data=null)
	{
	    $temp_array=array(
	        'ret'=>$ret,
	        'reason'=>$reason,
	        'data_info'=>null
	    );
	    if($data !== null)
	    {
	        $temp_array['data_info']=$data;
	    }
	    return $temp_array;
	}
} 